import java.io.*;
import java.sql.*;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class UI implements ActionListener{
	  private Connection con = null; //Database objects 
	  //連接object 
	  private Statement stat = null; 
	  //執行,傳入之sql為完整字串 
	  private ResultSet rs = null; 
	  //結果集 
	  private PreparedStatement pst = null; 
	  
	  private JFrame frame = new JFrame("資料庫設定");
	  private JPasswordField passwordField;
	  //執行,傳入之sql為預儲之字申,需要傳入變數之位置 
	  //先利用?來做標示  
	  String url = "jdbc:mysql://localhost:3306";
	  String user = "root"; 
	  String password = "";
	  
	  public boolean testCreatSQL() 
	  {
		
		try { 
			
		    Class.forName("com.mysql.jdbc.Driver"); 
		    //註冊driver 
		    con = DriverManager.getConnection(url,user,password);
		    //取得connection
	
		    //jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=Big5
		    //localhost是主機名,test是database名
		    //useUnicode=true&characterEncoding=Big5使用的編碼 
		      
		   } 
		   catch(ClassNotFoundException e1) 
		   { 
		     System.out.println("DriverClassNotFound :"+e1.toString()); 
		   }//有可能會產生sqlexception 
		   catch(SQLException x) {
			  JOptionPane.showMessageDialog(frame, "密碼錯誤請重新輸入", "Message", JOptionPane.INFORMATION_MESSAGE); 
		      return false;
			  //System.out.println("Exception :"+x.toString()); 
		   } 
		   return true;
	  }
	  //設定使用者介面
	  public UI(){
		  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		  JPanel Panel = new JPanel();
		  JPanel buttonPanel = new JPanel();
		  JPanel lablePanel = new JPanel();
		  JButton okButton = new JButton("OK");
		  //GridLayout frameLayout = new GridLayout(1,3);
		  //Panel.setLayout(frameLayout);
		  //buttonPanel.setLayout(frameLayout);
		  //lablePanel.setLayout(frameLayout);
		  
		  JLabel inputLabel = new JLabel("請輸入您的資料庫密碼:");
		  passwordField = new JPasswordField(12);
		  
		  lablePanel.add(inputLabel);
		  Panel.add(passwordField);
		  buttonPanel.add(okButton);
		  
		  passwordField.addActionListener(this);
		  passwordField.setActionCommand("OK");
		  
		  okButton.addActionListener(this);
		  okButton.setActionCommand("OK");
		  
		  
		  frame.getContentPane().add(Panel,BorderLayout.CENTER);
		  frame.getContentPane().add(lablePanel,BorderLayout.WEST);
		  frame.getContentPane().add(buttonPanel,BorderLayout.EAST);
		  
		  
		  frame.setSize(400 , 80);
		  frame.setVisible(true);		  	  		  
	  }
	 
	  //ActionListener actionListener =new ActionListener(){
	  public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		String cmd = e.getActionCommand();
		if(cmd.equals("OK")){
			char[] input = passwordField.getPassword();
			for(int i=0;i<input.length;i++)
				password += input[i];
			try {
				if(testCreatSQL()){ 
					createTable();					
					Close();
					CreateXML();
					CreateHistory();
					JFrame frame = new JFrame();
					JOptionPane.showMessageDialog(frame,"資料庫初始化設定完成");
					System.exit(0);
				}
				else{
					password = "";
					passwordField.selectAll();
					passwordField.requestFocusInWindow();
				}
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}	
			
			
		}
		else
		{
			System.out.println("error 111111111");
		}
	  }
	  
	  
	  private void CreateHistory() {
		// TODO Auto-generated method stub
		File history = new File("C:/History/");
		history.mkdir();
		history = new File("C:/History/general");
		history.mkdir();
	}
	//建立table的方式 
	  //可以看看Statement的使用方式 
	  public void createTable() throws IOException 
	  { 
		try 
	    { 
			stat = con.createStatement();
			stat.execute("create schema tcm");
			stat.execute("create table tcm.accounttable(id INT NOT NULL AUTO_INCREMENT" +
					",account VARCHAR(45) NULL,password VARCHAR(45) NULL," +
					"role VARCHAR(45) NULL,email VARCHAR(45) NULL,name VARCHAR(45) NULL,sex VARCHAR(45) NULL,education VARCHAR(45) NULL,marriage VARCHAR(45) NULL,job VARCHAR(45) NULL" +
					",liveWith VARCHAR(45) NULL,year VARCHAR(45) NULL,height VARCHAR(45) NULL,weight VARCHAR(45) NULL,PRIMARY KEY (id))");
			stat.execute("Insert into tcm.accounttable (account,password,role,email,name,sex,education,marriage,job,liveWith,year,height,weight) VALUES('pllab','d78ed45c17cf5ae67750ec75b5e22bf1','admin','pllabictm@gmail.com','administer','male','college','single','no','alone','1989','170','66') ");
			stat.execute("create table tcm.questiontable(id INT NOT NULL AUTO_INCREMENT,account VARCHAR(45) NULL,testtime VARCHAR(45) NULL,categoryname VARCHAR(45) NULL,PRIMARY KEY (id))");
			stat.execute("create table tcm.categorytable(id INT NOT NULL AUTO_INCREMENT,author VARCHAR(45) NULL,categoryname VARCHAR(45) NULL,PRIMARY KEY (id))");
			stat.execute("Insert into tcm.categorytable(author,categoryname)VALUES('admin','體質類型')");
			stat.execute("Insert into tcm.categorytable(author,categoryname)VALUES('admin','體徵類型')");
			stat.execute("create table tcm.casehistorytable(id INT NOT NULL AUTO_INCREMENT,account VARCHAR(45) NULL,history VARCHAR(100) NULL,PRIMARY KEY (id))");
	    
	    } 	
	    catch(SQLException e) 
	    { 
	      System.out.println("CreateDB Exception :" + e.toString()); 
	    }  
	  } 
	  //完整使用完資料庫後,記得要關閉所有Object 
	  //否則在等待Timeout時,可能會有Connection poor的狀況 
	  private void Close() 
	  { 
	    try 
	    { 
	      if(rs!=null) 
	      { 
	        rs.close(); 
	        rs = null; 
	      } 
	      if(stat!=null) 
	      { 
	        stat.close(); 
	        stat = null; 
	      } 
	      if(pst!=null) 
	      { 
	        pst.close(); 
	        pst = null; 
	      } 
	    } 
	    catch(SQLException e) 
	    { 
	      System.out.println("Close Exception :" + e.toString()); 
	    } 
	  } 
	  
	  public void CreateXML() throws IOException{
		  File file = new File("WebContent/META-INF/context.xml");
		  file.createNewFile();
		  Writer writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream("WebContent/META-INF/context.xml"), "UTF-8"));
		  writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
		  writer.write("<!--\n");
		  writer.write("  Licensed to the Apache Software Foundation (ASF) under one or more\n  contributor license agreements.  See the NOTICE file distributed with\n" +
		  		"this work for additional information regarding copyright ownership.\n  The ASF licenses this file to You under the Apache License, Version 2.0\n  (the \"License\"); "+
				  "you may not use this file except in compliance with\n  the License.  You may obtain a copy of the License at\n\n      \n\n  Unless required by applicable law or agreed to in writing, software\n  " +
		  		   "distributed under the License is distributed on an \"AS IS\" BASIS,\n  " + "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  "+"See the License for the specific language governing permissions and\n  "+
				  "limitations under the License.\n--><!-- The contents of this file will be loaded for each web application -->\n"+
		  		   "<Context antiJARLocking=\"true\" path=\"/ctmpllab\">\n\t<Resource name=\"jdbc/ctmpllab\"\n\t\tauth=\"Container\" type=\"javax.sql.DataSource\"\n\t\tmaxActive=\"100\" maxIdle=\"30\" maxWait=\"10000\" username=\"root\"\n\t\t" +
		  		   "password=\""+password+"\" driverClassName=\"com.mysql.jdbc.Driver\"\nurl=\"jdbc:mysql://localhost:3306/tcm?useUnicode=true&amp;characterEncoding=UTF8\"\n/>\n\t<!--\n\t<Resource name=\"jdbc/questionHistory\"\n\t\tauth=\"Container\" type=\"javax.sql.DataSource\"\n\t\t" + 
		  		   "maxActive=\"100\" maxIdle=\"30\" maxWait=\"10000\" username=\"root\"\n\t\tpassword=\""+password
		  		   +"\" driverClassName=\"com.mysql.jdbc.Driver\"\nurl=\"jdbc:mysql://localhost:3306/questiontable?useUnicode=true&amp;characterEncoding=UTF8\"\n/>\n\t-->\n\t<!-- Default set of monitored resources -->\n\t"+
		  		   "<WatchedResource>WEB-INF/web.xml</WatchedResource>\n\n\t<!-- Uncomment this to disable session persistence across Tomcat restarts -->\n\t<!--\n\t<Manager pathname=\"\" />\n\t-->\n\n\t<!-- Uncomment this to enable Comet connection tacking (provides events\n\t\t "+
		  		   "on session expiration as well as webapp lifecycle) -->\n\t<!--\n\t<Valve className=\"org.apache.catalina.valves.CometConnectionManagerValve\" />\n\t-->\n\t"+
		  		   "<Realm className=\"org.apache.catalina.realm.DataSourceRealm\"\n\t\tlocalDataSource=\"true\"\n\t\tdataSourceName=\"jdbc/ctmpllab\"\n\t\tuserTable=\"accounttable\" userNameCol=\"account\" userCredCol=\"password\"\n\t\tuserRoleTable=\"accounttable\" roleNameCol=\"role\" />\n\n</Context>");
		  writer.close();
	  }
	  public static void main(String[] args) 
	  { 	 
	    //測看看是否正常 
		 UI test = new UI(); 
	  }
	
}
